package david.java.flink_sql.udf;

import org.apache.flink.table.functions.ScalarFunction;

/**
 * @Description: split string into array by the specified separator, and select the Nth element.
 *               The index of head element is 0, and the tail is -1
 * @Author: David
 * @Date: Create in 4:32 下午 2022/1/19
 */
public class GetSplitString extends ScalarFunction {


    public String eval(String tarStr, String separator, int index) {
        if (tarStr == null) {
            return null;
        }

        if (separator == null) {
            throw new RuntimeException("GetSplitString ===> separator can not be null !!!");
        }

        String[] strs = tarStr.split(separator);

        if (index >= 0) {
            if (index > strs.length - 1) {
                throw new RuntimeException("GetSplitString ===>  |index| can not greater than array's length - 1");
            } else {
                return strs[index];
            }
        } else {
            if (-index > strs.length) {
                throw new RuntimeException("GetSplitString ===>  |index| can not greater than array's length");
            } else {
                return strs[strs.length + index];
            }
        }
    }

    public static void main(String[] args) {
        GetSplitString getSplitString = new GetSplitString();
        String str = "";
        // String str = "1144";
        System.out.println(getSplitString.eval(str, "-", 0));
        // System.out.println(getSplitString.eval(str, "-", 2));
        System.out.println(getSplitString.eval(str, "-", -1));
        // System.out.println(getSplitString.eval(str, "-", -2));
    }
}
